package com.adinnet.api.peaseRecord.service.impl;

import com.adinnet.api.appInform.mapper.AppInformMapper;
import com.adinnet.api.appInform.model.AppInform;
import com.adinnet.api.child.mapper.ChildMapper;
import com.adinnet.api.child.model.Child;
import com.adinnet.api.child.model.vo.ChildDetailsResp;
import com.adinnet.api.common.service.async.AsyncHandlerTask;
import com.adinnet.api.peaseLevel.mapper.PeaseLevelMapper;
import com.adinnet.api.peaseLevel.model.PeaseLevel;
import com.adinnet.api.peaseRecord.model.PeaseRecord;
import com.adinnet.api.peaseRecord.mapper.PeaseRecordMapper;
import com.adinnet.api.peaseRecord.model.VO.CollectPeaseResp;
import com.adinnet.api.peaseRecord.model.VO.PeaseRecordForm;
import com.adinnet.api.peaseRecord.model.VO.PeaseRecordPageResp;
import com.adinnet.api.peaseRecord.model.VO.ShareReq;
import com.adinnet.api.peaseRecord.service.PeaseRecordService;
import com.adinnet.api.peaseRule.service.PeaseRuleService;
import com.adinnet.api.rankLevel.mapper.RankLevelMapper;
import com.adinnet.api.rankLevel.model.RankLevel;
import com.adinnet.api.user.mapper.UserMapper;
import com.adinnet.api.user.model.User;
import com.adinnet.common.Constants;
import com.adinnet.common.jpush.PushBean;
import com.adinnet.common.peaseRule.enums.PeaseRule;
import com.adinnet.common.utils.PropertiesConfig;
import com.adinnet.common.utils.StringUtil;
import com.adinnet.core.JsonResult;
import com.adinnet.core.PageResp;
import com.adinnet.core.exception.BizException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 豌豆记录表 服务实现类
 * </p>
 *
 * @author chenjia
 * @since 2020-12-02
 */
@Service
public class PeaseRecordServiceImpl extends ServiceImpl<PeaseRecordMapper, PeaseRecord> implements PeaseRecordService {

    @Autowired
    private PeaseRecordMapper peaseRecordMapper;

    @Autowired
    private ChildMapper childMapper;

    @Autowired
    private RankLevelMapper rankLevelMapper;

    @Autowired
    private PeaseLevelMapper peaseLevelMapper;

    @Autowired
    private PeaseRuleService peaseRuleService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AppInformMapper appInformMapper;

    @Autowired
    private AsyncHandlerTask asyncHandlerTask;

    /**
     * 根据儿童id查询金豆记录
     * @param childId
     * @return
     */
    @Override
    public List<PeaseRecord> getPeaseRecords(Integer childId) {
        QueryWrapper<PeaseRecord> wrapper = new QueryWrapper();
        wrapper.eq("type",1).eq("child_id", childId).eq("status",0).eq("deleted",0)
                .ne("pease_num",0).groupBy("source").orderByAsc("source");
        return peaseRecordMapper.selectList(wrapper);
    }

    @Override
    @Transactional
    public JsonResult collectPease(Integer peaseId) {
        Child cd = new Child();
        CollectPeaseResp collectPeaseResp = new CollectPeaseResp();
        Boolean isUpgrade=false;
        PeaseRecord peaseRecord = peaseRecordMapper.selectById(peaseId);
        ChildDetailsResp c1 = childMapper.information(peaseRecord.getChildId());
        Child child = childMapper.selectById(peaseRecord.getChildId());
        cd.setId(peaseRecord.getChildId());
        peaseRecord.setStatus(1);
        Integer pl=child.getPeaseLevelId();
        Integer rl=child.getRankLevelId();
        if(pl!=null&&pl<8){
            pl++;
        }
        if(rl!=null&&rl<8){
            rl++;
        }
        RankLevel rankLevel = rankLevelMapper.selectById(rl);
        PeaseLevel peaseLevel = peaseLevelMapper.selectById(pl);
        Integer num=child.getPeaseNum()+peaseRecord.getPeaseNum();
        Integer totalNum=child.getSumPeaseNum()+peaseRecord.getPeaseNum();
        cd.setPeaseNum(num);
        cd.setSumPeaseNum(totalNum);
        if(rankLevel!=null&&totalNum>=rankLevel.getPeaseNum()){
            cd.setRankLevelId(rankLevel.getId());
        }
        if(peaseLevel!=null&&num>=peaseLevel.getPeaseNum()){ //金豆数已达到或超过下一阶段的所需金豆数
            cd.setPeaseLevelId(peaseLevel.getId());
            if(c1.getPeaseLevelId()!=peaseLevel.getId()){ //排除已达到最高等级继续收取金豆后提示已升级
                isUpgrade=true;  //已升级
            }
        }
        childMapper.updateById(cd);
        peaseRecordMapper.updateById(peaseRecord);
        //收取完成后返参判断
        ChildDetailsResp c = childMapper.information(peaseRecord.getChildId());
        collectPeaseResp.setIsUpgrade(isUpgrade);
        collectPeaseResp.setRankLevelId(c.getRankLevelId());
        collectPeaseResp.setRankLevel(c.getRankLevel());
        collectPeaseResp.setRankName(c.getRankName());
        collectPeaseResp.setPeaseLevelId(c.getPeaseLevelId());
        collectPeaseResp.setPeaseName(c.getPeaseName());
        collectPeaseResp.setRattanNum(c.getRattanNum());
        collectPeaseResp.setPeaseNum(c.getPeaseNum());
        //豆藤升级后返回给前端升级前后的文本，并发送系统消息
        if(isUpgrade){
            User user = userMapper.selectById(child.getUserId());
            collectPeaseResp.setPrePeaseName(c1.getPeaseName());
            collectPeaseResp.setUpgradePeaseName(c.getPeaseName());
            collectPeaseResp.setPrePeaseLevelId(c1.getPeaseLevelId());
            collectPeaseResp.setUpgradePeaseLevelId(c.getPeaseLevelId());
            AppInform inform = new AppInform();
            inform.setChildId(child.getId());
            inform.setSchoolId(child.getSchoolId());
            inform.setTitle("系统消息");
            inform.setContent("你的豆藤进入"+c.getPeaseName()+"阶段啦");
            inform.setType(1);
            inform.setReceiveUserId(user.getReceiveUserId());
            inform.setPubdate(new Date());
            inform.setType(1);
            appInformMapper.insert(inform);
            if(!StringUtil.isBlank(user.getReceiveUserId())){
                PushBean pushBean = new PushBean();
                pushBean.setAppKey(PropertiesConfig.pushAppKey);
                pushBean.setMasterSecret(PropertiesConfig.pushSecret);
                pushBean.setAlert("你的豆藤进入"+c.getPeaseName()+"阶段啦");
                pushBean.setTitle("系统消息");
                pushBean.setExtras(null);
                asyncHandlerTask.sendSystemInform(pushBean,user.getReceiveUserId());
            }

        }
        return JsonResult.ok().put("data",collectPeaseResp);
    }

    @Override
    @Transactional
    public JsonResult collectRattan(Integer childId) {
        //获取最高阶段的所需豆豆总数
        PeaseLevel peaseLevel = peaseLevelMapper.selectById(8);
        Integer  num=peaseLevel.getPeaseNum();
        Child cd = new Child();
        cd.setId(childId);
        Child child = childMapper.selectById(childId);
        if(child==null){
            return  JsonResult.error("获取儿童信息错误！");
        }
        Integer peaseNum = child.getPeaseNum();
        if(peaseNum<num){
            return  JsonResult.error("金豆不足，无法收取！");
        }
        Integer peaseLevelId = child.getPeaseLevelId();
        if(peaseLevelId!=8){
            return  JsonResult.error("豆藤尚未成熟无法收取！");
        }
        Integer rattanNum = child.getRattanNum();
        //生成一条已收获的豆藤记录
        rattanNum++;
        PeaseRecord record = new PeaseRecord();
        record.setType(2);
        record.setChildId(childId);
        record.setPeaseNum(1);
        record.setSource(10);
        record.setStatus(1);
        record.setSourceName("收获豆藤");
        peaseRecordMapper.insert(record);
        //生成一条已扣除的金豆记录
        peaseNum-=num;
        peaseLevelId=1;
        PeaseRecord record2 = new PeaseRecord();
        record2.setType(1);
        record2.setChildId(childId);
        record2.setPeaseNum(-num);
        record2.setSource(10);
        record2.setStatus(3);
        record2.setSourceName("收获豆藤");
        peaseRecordMapper.insert(record2);
        //修改儿童的金豆数，豆藤数，豆藤期
        cd.setPeaseNum(peaseNum);
        cd.setRattanNum(rattanNum);
        cd.setPeaseLevelId(peaseLevelId);
        childMapper.updateById(cd);
        return JsonResult.ok("豆藤收获成功");
    }

    @Override
    public JsonResult getPeaseRecordList(PeaseRecordForm form) {
        Child child = childMapper.selectById(form.getChildId());
        PeaseRecordPageResp recordPageResp = new PeaseRecordPageResp();
        recordPageResp.setPeaseNum(child.getPeaseNum());
        recordPageResp.setRattanNum(child.getRattanNum());
        /*QueryWrapper<PeaseRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("child_id",form.getChildId()).eq("type",form.getType());
        queryWrapper.ne("pease_num",0);
        queryWrapper.in("status",1,3);
        if(form.getStatus()==1){
            queryWrapper.eq("status",1);
        }
        if(form.getStatus()==2){
            queryWrapper.eq("status",3);
        }
        queryWrapper.orderByDesc("created_date");*/
        //由于分享获得的金豆来源都是存的code，所以对于分享的情况，需要额外判断，处理成文本
        Page<PeaseRecord> page = new Page<>(form.getPage(), form.getLimit());
        List<PeaseRecord> list = baseMapper.getPeaseRecordDetails(page, form);
        recordPageResp.setCount(page.getTotal());
        recordPageResp.setRecords(list);
        return JsonResult.ok().put("data",recordPageResp);
    }

    /**
     * @param shareReq:
     * @Description: 分享
     * @author zYshuai
     * @Date: 2020/12/10 10:18
     * @return: com.adinnet.core.JsonResult
     */
    @Override
    public JsonResult share(ShareReq shareReq) {
        QueryWrapper<PeaseRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0).eq("child_id", shareReq.getChildId()).last(" AND DATE_FORMAT(created_date,'%Y-%m-%d')=DATE_FORMAT(now(),'%Y-%m-%d')");
        com.adinnet.api.peaseRule.model.PeaseRule ruleByCode = null;
        switch (shareReq.getSourceName()) {
            case Constants.SHARE_STUDY_QQ:
                //每天首次学习，QQ分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_STUDY_QQ);
                List<PeaseRecord> studyQQRecord = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(studyQQRecord)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                //将待分享的豆豆数清空
                updateChildSharePeaseNum(shareReq.getChildId());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");
            case Constants.SHARE_STUDY_WECHAT:
                //每天首次学习，微信分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_STUDY_WECHAT);
                List<PeaseRecord> share_study_wechat = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(share_study_wechat)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                //将待分享的豆豆数清空
                updateChildSharePeaseNum(shareReq.getChildId());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");
            case Constants.SHARE_STUDY_WECHAT_FRIENDS:
                //每天首次学习，微信朋友圈分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_STUDY_WECHAT_FRIENDS);
                List<PeaseRecord> share_study_wechat_friends = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(share_study_wechat_friends)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                //将待分享的豆豆数清空
                updateChildSharePeaseNum(shareReq.getChildId());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");
            case Constants.SHARE_STUDY_DINGDING:
                //每天首次学习，钉钉分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_STUDY_DINGDING);
                List<PeaseRecord> share_study_dingding = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(share_study_dingding)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                //将待分享的豆豆数清空
                updateChildSharePeaseNum(shareReq.getChildId());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");

            case Constants.SHARE_SHOPPING_QQ:
                //每天首次购物，QQ分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_SHOPPING_QQ);
                List<PeaseRecord> share_shopping_qq = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(share_shopping_qq)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");

            case Constants.SHARE_SHOPPING_WECHAT:
                //每天首次购物，微信分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_SHOPPING_WECHAT);
                List<PeaseRecord> share_shopping_wechat = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(share_shopping_wechat)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");

            case Constants.SHARE_SHOPPING_WECHAT_FRIENDS:
                //每天首次购物，微信朋友圈分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_SHOPPING_WECHAT_FRIENDS);
                List<PeaseRecord> share_shopping_wechat_friends = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(share_shopping_wechat_friends)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");
            case Constants.SHARE_SHOPPING_DINGDING:
                //每天首次购物，钉钉分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_SHOPPING_DINGDING);
                List<PeaseRecord> share_shopping_dingding = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(share_shopping_dingding)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");
            case Constants.SHARE_MYSELF_QQ:
                //每天首次我的，QQ分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_MYSELF_QQ);
                List<PeaseRecord> share_myself_qq = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(share_myself_qq)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");
            case Constants.SHARE_MYSELF_WECHAT:
                //每天首次我的，微信分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_MYSELF_WECHAT);
                List<PeaseRecord> share_myself_wechat = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(share_myself_wechat)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");

            case Constants.SHARE_MYSELF_WECHAT_FRIENDS:
                //每天首次我的，微信朋友圈分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_MYSELF_WECHAT_FRIENDS);
                List<PeaseRecord> share_myself_wechat_friends = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(share_myself_wechat_friends)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");

            case Constants.SHARE_MYSELF_DINGDING:
                //每天首次我的，钉钉分享获得金豆
                wrapper.eq("source_name", Constants.SHARE_MYSELF_DINGDING);
                List<PeaseRecord> share_myself_dingding = peaseRecordMapper.selectList(wrapper);
                if (CollectionUtils.isNotEmpty(share_myself_dingding)) {
                    return JsonResult.ok("分享成功!");
                }
                ruleByCode = peaseRuleService.getPeaseRuleByCode(shareReq.getSourceName());
                insertPeaseRecord(shareReq, ruleByCode.getPeaseNum(), shareReq.getSourceName());
                return JsonResult.ok("分享成功+" + ruleByCode.getPeaseNum() + "金豆");
            default:
                throw new BizException("请选择正确的分享方式!");
        }
    }

    @Override
    public void testJg(Integer childId) {
        Child child = childMapper.selectById(childId);
        User user = userMapper.selectById(child.getUserId());
        /*ChildDetailsResp c = childMapper.information(childId);
        AppInform inform = new AppInform();
        inform.setChildId(child.getId());
        inform.setSchoolId(child.getSchoolId());
        inform.setTitle("系统消息");
        inform.setContent("你的豆藤进入"+c.getPeaseName()+"阶段啦");
        inform.setType(1);
        inform.setReceiveUserId(user.getReceiveUserId());
        inform.setPubdate(new Date());
        inform.setType(1);
        appInformMapper.insert(inform);*/
        PushBean pushBean = new PushBean();
        pushBean.setAppKey(PropertiesConfig.pushAppKey);
        pushBean.setMasterSecret(PropertiesConfig.pushSecret);
        pushBean.setAlert("极光推送测试");
        pushBean.setTitle("系统消息");
        pushBean.setExtras(null);
        asyncHandlerTask.sendSystemInform(pushBean,user.getReceiveUserId());
    }

    //新增豌豆记录
    private void insertPeaseRecord(ShareReq shareReq, Integer peaseNum, String sourceName) {
        PeaseRecord record = new PeaseRecord();
        record.setType(1);
        record.setChildId(shareReq.getChildId());
        record.setPeaseNum(peaseNum);
        record.setSource(2);
        record.setSourceName(sourceName);
        record.setStatus(0);
        peaseRecordMapper.insert(record);
    }

    //学习分享 需要将待分享的豆豆数清空
    public void updateChildSharePeaseNum(Integer childId) {
        Child child = new Child();
        child.setSharePeaseNum(0);
        childMapper.update(child, new QueryWrapper<Child>().eq("id", childId));
    }
}
